<template>
  <div class="modal">
    <div class="mask" @click="changIsShowLoginModal(false)"></div>
    <div class="loginBox">
      <div class="close" @click="changIsShowLoginModal(false)"></div>
      <section class="nav">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号码登录</a
        >
        |
        <a href="#" :class="{ active: !isShowContent }" @click="showQR"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <!-- 手机号码登录 -->
        <div class="phoneLogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="arr"
            ></slide-verify>
          </div>
          {{ msg }}
          <div class="row">
            <input
              type="text"
              placeholder="请输入验证码"
              class="ipt"
              v-model="code"
            />
            <button class="btnCode" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btnCode" v-show="isShowCount">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="btnLogin" @click="submiFn">登录</button>
          </div>
        </div>
        <!-- 微信扫码登录 -->
        <div class="qrLogin" v-show="!isShowContent" id="weixin">
          微信扫码内容
        </div>
      </div>
    </div>
  </div>
</template>
 
<script>
import { mapActions, mapMutations } from "vuex";
import { sendSMSAPI, phoneRegin, wechatBindingAPI } from "@/request/api";
// 引入封装好的工具函数
import { validateTelephoneNumber } from "@/utils";
export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      arr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
      phoneNumber: "",
      count: 5,
      isShowCount: false,
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      //   方法:'模块名称/方法'
      changIsShowLoginModal: "showModal/changIsShowLoginModal",
      changeIsShowLogin: "loginStatus/changeIsShowLogin",
    }),
    ...mapActions({
      asyncchangeIsShowToast: "showToast/asyncchangeIsShowToast",
      asyncUpdateUserInfo: "userInfo/asyncUpdateUserInfo",
    }),
    // 微信扫码切换
    showQR() {
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,DQouaW1wb3dlckJveCAudGl0bGUsLmltcG93ZXJCb3ggLmluZm97DQogICAgZGlzcGxheTogbm9uZTsNCn0gICAgDQouaW1wb3dlckJveCBxcmNvZGV7DQogICAgbWFyZ2luLXRvcDogMjBweDsNCn0=",
      });
    },
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 倒计时
    daojishi() {
      // 验证成功后进入倒计时60s;
      // 显示倒计时
      this.isShowCount = true;
      let timer = setInterval(() => {
        // 递减
        this.count--;
        if (this.count < 0) {
          this.count = 5;
          //   停止、清空定时器
          clearInterval(timer);
          // 隐藏倒计时
          this.isShowCount = false;
        }
      }, 1500);
    },
    // 封装两个验证判断
    toVeify() {
      //   1.判断手机号码是否正确
      // let reg =
      //   /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!validateTelephoneNumber(this.phoneNumber)) {
        this.asyncchangeIsShowToast({
          isShow: true,
          msg: "请输入手机号码",
          type: "danger",
        });
        return;
      }
      // 2.滑动拼图是否正确
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        this.asyncchangeIsShowToast({
          isShow: true,
          msg: "请滑动拼图",
          type: "danger",
        });
        return;
      }
      // 被调用后，如果两个验证都成功后才可以继续执行下面的代码(不然就会发生验证不通过还继续往下执行)
      return true;
    },
    // 登录
    async submiFn() {
      // 1.判断手机号码是否正确
      // 2.滑动拼图是否正确
      if (!this.toVeify()) return;
      // 3.短信验证码不正确提示
      // 由于目前后台未返回正确验证码，所以只能做非空校验
      if (this.code.trim() == "") {
        this.asyncchangeIsShowToast({
          isShow: true,
          msg: "请输入验证码",
          type: "warning",
        });
        return;
      }

      // 手机绑定微信
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await wechatBindingAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid,
        });
        // console.log("手机绑定微信登录res:", res);
      } else {
        // 4.发起登录请求
        res = await phoneRegin({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }
      if (!res) return;
      // 5.提示用户登录成功
      alert("登录成功");
      // 6.存储token
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 7.隐藏登录窗口
      this.changIsShowLoginModal(false);
      // 8.topbar中登录状态的切换
      this.changeIsShowLogin(true);
      // 如果有uuid,清除code
      if (uuid) {
        this.$router.push(this.$route.path);
      }
      // 清除uuid
      localStorage.removeItem("uuid");
      // 获取用户信息
      this.asyncUpdateUserInfo();
    },
    // 验证
    async getCode() {
      // 1.判断手机号码是否正确
      // 2.滑动拼图是否正确
      if (!this.toVeify()) return;
      //   3.验证成功后发送请求
      let res = await sendSMSAPI({
        phone: this.phoneNumber,
      });
      // console.log("发送短信验证码res:", res);
      if (!res) return;
      alert("发送成功");
      // 调用倒计时
      this.daojishi();
    },
  },
};
</script>
 
<style lang = "less" scoped>
#weixin {
  /* background-color: #fcf; */
  display: flex;
  justify-content: center;
  margin-top: -20px;
}
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    margin: auto;
    width: 555px;
    height: 423px;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: url("../assets/img/login-box-bg.png") no-repeat;
    .close {
      position: absolute;
      right: 56px;
      top: 14px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png") no-repeat;
    }
    .nav {
      padding-top: 50px;
      text-align: center;
      margin-bottom: 20px;
      a {
        text-decoration: none;
        padding: 0 10px;
        color: #999;
        &.active {
          color: #000;
        }
      }
    }
    .content {
      width: 355px;
      height: 300px;
      margin: 10px auto 0;
      /* background: pink; */
    }
    .phoneLogin {
      .row {
        display: flex;
        margin-bottom: 20px;
        .ipt {
          box-sizing: border-box;
          flex: 1;
          height: 50px;
        }
        .btnCode {
          color: #fff;
          background: #083490;
          margin-left: 10px;
          width: 84px;
        }
        .btnLogin {
          color: #fff;
          background: #083490;
          height: 50px;
          width: 100%;
        }
      }
    }
  }
}
/* /deep/深入修改子组件的样式,如果缺少此,无法修改 */
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>